package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.User;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		String uri = httpServletRequest.getRequestURI();
//		System.out.println("uri:" + uri);
		StringBuffer url = httpServletRequest.getRequestURL();
//		System.out.println("url:" + url);
		String servletPath = httpServletRequest.getServletPath();
//		System.out.println("servletPath" + servletPath);
		
		if ("/login.jsp".equals(servletPath)
			|| "/checkImg".equals(servletPath)
			|| "/loginServlet".equals(servletPath)
			|| "/index.jsp".equals(servletPath)
			|| "/register.jsp".equals(servletPath)			
			|| "/registerServlet".equals(servletPath)
			|| "/login_old.jsp".equals(servletPath)
			|| servletPath.endsWith(".css")
			|| servletPath.endsWith(".js")
			|| servletPath.endsWith(".jpg")
			|| servletPath.endsWith(".png")
			|| servletPath.endsWith(".gif")) {
				chain.doFilter(request, response);
				return;
		}
		
		// 登录验证
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("user");
		if (null == user) {
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
			return;
		}

		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

}
